package Tree;

public class p530二叉搜索树的最小绝对差 {
    class Solution {
        // 中序遍历二叉搜索树得到的是递增的序列，使用pre记录前一个结点，cur记录当前节点，
        // result记录当前节点与前一结点差值的绝对值
        int result = Integer.MAX_VALUE;
        TreeNode pre;
        public int getMinimumDifference(TreeNode root) {
            inOrder(root);
            return result;
        }

        public void inOrder(TreeNode cur){
            if (cur == null) return;
            // 左
            inOrder(cur.left);
            // 中
            if (pre != null) result = Math.min(result, Math.abs(pre.val - cur.val));
            // 记录前一结点
            pre = cur;
            // 右
            inOrder(cur.right);
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
